#ifndef SERIAL_SOCKET_HPP
#define SERIAL_SOCKET_HPP

#include <stdint.h>

#define SS_MAX_PAYLOAD_SIZE (512)

#define SS_PACKET_TYPE_DATA (0x0000)
#define SS_PACKET_TYPE_RESP (0x0001)
#define SS_PACKET_RESP_SUCCESS  (0x0000)
#define SS_PACKET_RESP_FAILED   (0x8000)
#define SS_PACKET_RESP_SIZEERR  (0x8001)
#define SS_PACKET_RESP_CRCERR   (0x8002)
#define SS_PACKET_RESP_NOLISTEN (0x8003)
#define SS_PACKET_RESP_NOREAD   (0x8004)
#define SS_PACKET_RESP_IDERR    (0x8005)


struct SerialSocketFrameHeader {
    uint16_t type;
    uint16_t port_number;
    uint16_t packet_id;
    uint16_t size;
}__attribute__((packed));

class SerialSocketPortable {
public:
    /* 串口移植相关. */
    virtual bool open() = 0;
    virtual bool close() = 0;
    virtual unsigned int read(void *buffer,unsigned int size) = 0;
    virtual unsigned int write(const void *buffer,unsigned int size) = 0;
    /* 操作系统移植相关. */
    virtual int getSemaphore(bool is_mutex) = 0;
    virtual bool freeSemaphore(int sem_number) = 0;
    virtual bool takeSemaphore(int sem_number,int timeout) = 0;
    virtual bool releaseSemaphore(int sem_number) = 0;
};

class SerialSocket {
public:
    virtual ~SerialSocket();
    virtual bool open() = 0;
    virtual bool close() = 0;
    virtual unsigned int read(void *buffer,unsigned int size) = 0;
    virtual unsigned int write(const void *buffer,unsigned int size) = 0;
    virtual int getPortNumber() = 0;
};

class SerialSockets{
public:
    virtual ~SerialSockets();
    virtual bool open() = 0;
    virtual bool close() = 0;
    virtual SerialSocket *get(int port_number) = 0;
    virtual bool free(SerialSocket *instance) = 0;
    virtual void eventHandler() = 0;
    static SerialSockets *getInstance(SerialSocketPortable *portable,unsigned int buffer_size);
    static bool freeInstance(SerialSocket *instance);
};

#endif
